/*
 * @Author: Wangtao
 * @Date: 2021-03-25 16:19:28
 * @LastEditors: Wangtao
 * @LastEditTime: 2022-04-21 17:40:00
 */

import { CommonModule } from '@/store/modules/common'

export function checkPermission (el: any, binding, type?: string) {
  const { value } = binding
  const functions = CommonModule.session && CommonModule.session.user && type === 'limits' ? CommonModule.session.user.limits : CommonModule.session.user.functions
  if (value && value instanceof Array) {
    if (value.length > 0) {
      const permissionRoles = value

      const hasPermission = functions.some(role => {
        return permissionRoles.includes(role)
      })
      if (!hasPermission) {
        if (el && el.parentNode) {
          el.parentNode.removeChild(el)
        }
      } else {
        return true
      }
    }
  } else {
    throw new Error('\'need functions! Like v-functions="[admin,editor]\'')
  }
  return false
}

// export function hasPermission (permissionRoles: any = [], type = 'functions') {
//   const functions = CommonModule.session && CommonModule.session.user && type === 'limits' ? CommonModule.session.user.limits : CommonModule.session.user.functions
//   const hasPermission = functions.some(role => {
//     return permissionRoles.includes(role)
//   })
//   return hasPermission;
// }

export default (Vue) => {
  Vue.directive('functions', {
    inserted (el, binding) {
      checkPermission(el, binding)
    },
    update (el, binding) {
      checkPermission(el, binding)
    }
  })
}
